package com.fingard.dsp.bank.directbank.bocom13;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.directbank.bocom13.util.MD5;
import com.fingard.dsp.bank.reqrespobj.authforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryAuthForRecDetail;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryRecAuthInfoDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.TcpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.GZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.*;
import java.util.Calendar;
import java.util.Date;

/**
 * 交通银行批量代扣签约授权
 * 
 * 参考文档：
 *   	1、交通银行资金清算平台批量数据传送接口V1.0.doc
 * 		2、交通银行资金清算平台数据字典V1.0.doc
 * 		3、交通银行资金清算平台联机交易接口V1.0.doc
 * 
 * @author Cruise
 * @date 2019/10/11
 */
public class BOCOM13AuthorizeForRec extends BOCOM13Base implements IAuthorizeForRec {
	/**
	 * 开发接口：
	 * 		1、4.3.1	存量签约文件
	 * 		2、3.2.1	【报文1】结构说明
	 * 		3、3.2.2	【报文2】结构说明
	 * 		4、3.2.3	【报文3】结构说明
	 * 		5、3.2.4	【报文4】结构说明
	 * 		6、3.2.5	【报文5】结构说明
	 * 		7、5.1	文件确认（B60911/I60911）
	 */
	@Override
	public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) throws Exception {
		RetAtsAuthForRec retAts = new RetAtsAuthForRec(p_req.reqHeader);
		retAts.reqSeqID = p_req.reqSeqID;

		TcpPortClient tmpClient = null;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
        	String tmpPayDate = Format.Date8Format.format(new Date());
			
			String bankBranch = getBankConfig().getMapValueByKey("bankBranch", p_req.ownAct);
			if (StringHelper.isNullOrEmpty(bankBranch)) {
				retAts.respCode = "0";
				retAts.respInfo = "未配置账号[" + p_req.ownAct + "]银行方分支机构映射,请检查config.xml中'bankBranch'配置项";
				retAts.reqSeqID = p_req.reqSeqID;
				retAts.writeRetToATS();
				return retAts;
			}

            String corpNo = getBankConfig().getMapValueByKey("corpNoMapping", p_req.ownAct);
            if (StringHelper.isNullOrEmpty(corpNo)) {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]保险方ID映射,请检查BOCOM13/config.xml中'corpNoMapping'节点配置";
                retAts.reqSeqID = p_req.reqSeqID;
                retAts.writeRetToATS();
                return retAts;
            }

			String fileType = BOCOM13TransCode.batSign_ENDIIMPT;
			String tmpBatSeqNo = getBatSeqNo(getENDIIMPTDirectory(), 5);
			
			String tmpUploadFileName = "I_B_" + tmpPayDate + "_" + corpNo + "_" + bankBranch + "_" + fileType + ".S." + tmpBatSeqNo;
			String tmpLocalFilePath = createENDIIMPTDirectory() + File.separator + tmpUploadFileName;
            File tmpLocalFile = new File(tmpLocalFilePath);
            if (!tmpLocalFile.exists()) {
                tmpLocalFile.createNewFile();
            }
            WriteBankLogLn2("待压缩批次签约授权请求文件保存本机路径:\r\n" + tmpLocalFilePath);
            WriteBankLogLn2("待压缩批次签约授权请求文件开始写入数据...");

			byte tmpByteSp = 0x0F;// 域分隔符
			byte tmpByteLn = (byte) '\n';// 换行符

            fos = new FileOutputStream(tmpLocalFilePath);
            fos.write("3012900".getBytes(getCharset()));/* 银行方ID:(3012900:交通银行) */
            fos.write(tmpByteSp);

            fos.write(bankBranch.getBytes(getCharset()));/* 银行分行代码:保险公司发起方账号开户分行代码 */
            fos.write(tmpByteSp);

            fos.write(tmpByteSp);/* 银行方业务日期 */
            fos.write(tmpByteSp);/* 银行方交易日期 */
            fos.write(tmpByteSp);/* 银行方交易时间 */
            fos.write(tmpByteSp);/* 银行方批次号 */

            fos.write(corpNo.getBytes(getCharset()));/*保险方ID: 保险公司编码 */
            fos.write(tmpByteSp);

            fos.write(tmpPayDate.getBytes(getCharset()));/* 保险方业务日期(yyyyMMdd) */
            fos.write(tmpByteSp);

            fos.write(tmpPayDate.getBytes(getCharset()));/* 保险方交易日期(yyyyMMdd) */
            fos.write(tmpByteSp);

            fos.write(Format.Time6Format.format(new Date()).getBytes(getCharset()));/* 保险方交易时间 */
            fos.write(tmpByteSp);

            fos.write(p_req.reqSeqID.getBytes(getCharset()));/* 保险方批次号 */
            fos.write(tmpByteSp);

            fos.write(p_req.totalNum.getBytes(getCharset()));/* 总笔数 */
            fos.write(tmpByteSp);

            fos.write(tmpByteSp);/* 成功笔数 */
            fos.write(tmpByteSp);/* 预留字段01 */
            fos.write(tmpByteSp);/* 预留字段02 */
            fos.write(tmpByteSp);/* 预留字段03 */
            fos.write(tmpByteSp);/* 预留字段04 */
            fos.write(tmpByteSp);/* 预留字段05 */
            fos.write(tmpByteSp);/* 预留字段06 */
            fos.write(tmpByteSp);/* 预留字段07 */
            fos.write(tmpByteSp);/* 预留字段08 */
            fos.write(tmpByteSp);/* 预留字段09 */
                                 /* 预留字段10 */

			int tmpRdCount = 0;
			while (p_req.readRecord()) {
				tmpRdCount++;

                fos.write(tmpByteLn);
                fos.write(String.valueOf(tmpRdCount).getBytes(getCharset()));/* 记录序号 */
                fos.write(tmpByteSp);

                fos.write(tmpByteSp);/* 应答类型 */
                fos.write(tmpByteSp);/* 错误码 */
                fos.write(tmpByteSp);/* 错误说明 */
                fos.write(tmpByteSp);/* 银行方业务日期 */
                fos.write(tmpByteSp);/* 银行方流水号 */

                fos.write(tmpPayDate.getBytes(getCharset()));/* 保险方业务日期 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.authCode.getBytes(getCharset()));/* 保险方流水号 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.insuPolicyNum.getBytes(getCharset()));/* 投保单号 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.sourceNoteCode.getBytes(getCharset()));/* 保单号 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.oppActName.getBytes(getCharset()));/* 客户姓名 */
                fos.write(tmpByteSp);

                fos.write(convertCertTypeToBank(p_req.readedDetail.certType).getBytes(getCharset()));/* 证件类型 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.certNum.getBytes(getCharset()));/* 证件号码 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.oppAct.getBytes(getCharset()));/* 账号 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.cellPhone.getBytes(getCharset()));/* 手机号码 */
                fos.write(tmpByteSp);

                fos.write(p_req.readedDetail.authCode.getBytes(getCharset()));/* 代收协议编号 */
                fos.write(tmpByteSp);

                fos.write(tmpByteSp);/* 预留字段01 */
                fos.write(tmpByteSp);/* 预留字段02 */
                fos.write(tmpByteSp);/* 预留字段03 */
                fos.write(tmpByteSp);/* 预留字段04 */
                fos.write(tmpByteSp);/* 预留字段05 */
                fos.write(tmpByteSp);/* 预留字段06 */
                fos.write(tmpByteSp);/* 预留字段07 */
                fos.write(tmpByteSp);/* 预留字段08 */
                fos.write(tmpByteSp);/* 预留字段09 */
												/* 预留字段10 */
			}
			WriteBankLogLn2("批量代收签约授权请求文件内容:\r\n" + FileHelper.readFileText(tmpLocalFilePath, getCharset()));

            String tmpGZipFilePath = tmpLocalFilePath + ".gz";
            WriteBankLogLn2("压缩后批次签约授权请求文件保存本机路径:\r\n" + tmpGZipFilePath);
            WriteBankLogLn2("压缩后批次签约授权请求文件开始进行压缩...");
			GZipHelper.doCompressFile(tmpLocalFilePath, tmpGZipFilePath);
            WriteBankLogLn2("压缩后批次签约授权请求文件开始压缩完成.");

			// 2.文件传输
			// 2.1 报文1
            WriteBankLogLn2("压缩后批次签约授权请求文件开始进行文件传输[报文1->报文5]...");
			StringBuilder tmpSbPck1 = new StringBuilder();
			tmpSbPck1.append("I60901");/* 交易码 */
			tmpSbPck1.append("I");/* 文件创建方标识 */
			tmpSbPck1.append("B");/* 文件接收方标识 */
			tmpSbPck1.append(String.format("%-15s", corpNo));/* 保险方ID */
			tmpSbPck1.append(String.format("%-10s", "3012900"));/* 银行方ID */
			tmpSbPck1.append(String.format("%-20s", bankBranch));/* 银行分行代码 */
			tmpSbPck1.append(tmpPayDate);/* 业务日期 */
			tmpSbPck1.append(String.format("%-20s", p_req.reqSeqID));/* 交易流水号 */
			tmpSbPck1.append(tmpPayDate);/* 交易日期 */
			tmpSbPck1.append(Format.Time6Format.format(new Date()));/* 交易时间 */
			tmpSbPck1.append(String.format("%-128s", tmpUploadFileName + ".gz"));/* 压缩文件名称 */
			tmpSbPck1.append(String.format("%012d", new File(tmpGZipFilePath).length()));/* 文件大小 */
			int maxBlockSize = 2097152;
			int tmpBlockSize = (int) new File(tmpGZipFilePath).length();
			if (tmpBlockSize > maxBlockSize) {
				tmpBlockSize = maxBlockSize;
			}
			tmpSbPck1.append(String.format("%08d", tmpBlockSize));/* 数据包大小 */
			String tmpGZMD5 = MD5.generateFileMD5(tmpGZipFilePath);
			tmpSbPck1.append(String.format("%-200s", tmpGZMD5));/* 文件MD5校验值 */
			tmpSbPck1.append(String.format("%-1500s", ""));

			fis = new FileInputStream(tmpGZipFilePath);
			boolean tmpFinished = false;
			String tmpFileInfoCode = "";
			String tmpFileMsg = "";

			int tmpStep = 1;
			int tmpReadedLen = 0;
			byte[] tmpLastBuffer = new byte[0];
			int tmpLastBufLength = 0;
			byte[] tmpNowBuffer = new byte[0];
			int tmpNowBufLength = 0;
			int tmpLastSeq = -1;
			String tmpBankAskSeq = "";// 数据包序号

			tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.filePort), this);
			WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + bankFront.filePort + "]。");

			String[] tmpBkRet = new String[] { "", "" };
			while (tmpReadedLen <= new File(tmpGZipFilePath).length()) {
				if (tmpStep == 1) {
					WriteBankLogLn("发送银行的【报文1】请求数据:\r\n" + tmpSbPck1);
					tmpBkRet = sendToBank(tmpSbPck1.toString(), tmpClient);
					tmpStep++;
				} else {
					byte[] bytesBody3 = ("I60902" + tmpBankAskSeq).getBytes(getCharset());
					WriteBankLogLn("发送银行的报文3请求数据，不包含数据包为:" + "I60902" + tmpBankAskSeq);
					byte[] bytesP3ToSend = new byte[bytesBody3.length + tmpNowBufLength];
					System.arraycopy(bytesBody3, 0, bytesP3ToSend, 0, bytesBody3.length);
					System.arraycopy(tmpNowBuffer, 0, bytesP3ToSend, bytesBody3.length, tmpNowBufLength);
					WriteBankLogLn2("当前【报文3】报文体字节数:" + bytesP3ToSend.length);
					WriteBankLogLn2("发送【报文3】请求报文体数据:\r\n" + new String(bytesP3ToSend, getCharset()));
					WriteBankLogLn("开始发送【报文3】...");
					tmpBkRet = sendToBank(bytesP3ToSend, tmpClient);
					tmpLastBuffer = tmpNowBuffer;
					tmpLastBufLength = tmpNowBufLength;
					tmpLastSeq = Integer.parseInt(tmpBankAskSeq);
				}
				tmpBankAskSeq = "";
				tmpNowBuffer = new byte[0];
				tmpNowBufLength = 0;

				if (tmpBkRet[0].length() == 0) {
					byte[] bytesBkRet = tmpBkRet[1].getBytes(getCharset());
					if (bytesBkRet.length > 24) {
						tmpBankAskSeq = new String(bytesBkRet, 25, 6);
						byte tmpRespType = bytesBkRet[24];
						if (tmpRespType == 'G') {
							WriteBankLogLn("响应报文类型为【报文2】,请求包:" + tmpBkRet[1]);
							tmpBankAskSeq = new String(bytesBkRet, 25, 6);
							WriteBankLogLn("【报文2】响应数据中数据包序号：" + tmpBankAskSeq);
							int tmpAskSeq = Integer.parseInt(tmpBankAskSeq);
							int expectedSeq = tmpLastSeq + 1;
							if (tmpAskSeq == expectedSeq) {// 继续读取文件
								tmpNowBuffer = new byte[maxBlockSize];
								tmpNowBufLength = fis.read(tmpNowBuffer, 0, tmpNowBuffer.length);
								WriteBankLogLn2("当前读取字节数:" + tmpNowBufLength);
								if (tmpNowBufLength > 0) {
									tmpReadedLen += tmpNowBufLength;
									WriteBankLogLn2("当前实际读取字节数:" + tmpReadedLen);
								} else {
									tmpFinished = false;
									tmpFileMsg = "数据包序号[" + tmpAskSeq + "]已无数据可读!";
									break;
								}
							} else {
								tmpFinished = false;
								tmpFileMsg = "数据包序号" + tmpAskSeq + "与预期序号" + expectedSeq + "不符";
								break;
							}
						} else if (tmpRespType == 'R') {
							WriteBankLogLn("响应报文类型为【报文2】,重传包:" + tmpBkRet[1]);
							tmpBankAskSeq = new String(bytesBkRet, 25, 6);
							WriteBankLogLn("【报文2】请求重传数据包序号：" + tmpBankAskSeq);
							int tmpReSendSeq = Integer.parseInt(tmpBankAskSeq);
							if (tmpReSendSeq == tmpLastSeq) {// 继续读取文件
								tmpNowBuffer = tmpLastBuffer;
								tmpNowBufLength = tmpLastBufLength;
							} else {
								tmpFinished = false;
								tmpFileMsg = "重传数据包序号" + tmpReSendSeq + "与上次序号" + tmpLastSeq + "不符";
								break;
							}
						} else if (tmpRespType == 'N') {
							WriteBankLogLn("响应报文类型为【报文4】:\r\n" + tmpBkRet[1]);
							WriteBankLogLn("3.【报文4】N-文件传输成功：" + tmpBankAskSeq);
							tmpFinished = true;
							break;
						} else if (tmpRespType == 'E') {
							WriteBankLogLn("响应报文类型为【报文5】:\r\n" + tmpBkRet[1]);
							WriteBankLogLn("3.【报文5】E-文件传输失败：" + tmpBankAskSeq);
							tmpFinished = false;
							tmpFileInfoCode = new String(bytesBkRet, 25, 6).trim();
							tmpFileMsg = new String(bytesBkRet, 31, 300).trim();
							break;
						} else if (tmpRespType == 'A') {
							WriteBankLogLn("响应报文类型为【报文5】:\r\n" + tmpBkRet[1]);
							WriteBankLogLn("【报文5】A-文件传输异常：" + tmpBankAskSeq);
							tmpFinished = false;
							tmpFileInfoCode = new String(bytesBkRet, 25, 6).trim();
							tmpFileMsg = new String(bytesBkRet, 31, 300).trim();
							break;
						} else {
							WriteBankLogLn("无法识别的响应报文:\r\n" + tmpBkRet[1]);
							WriteBankLogLn("3.【报文2】不能识别的应答类型：" + (char) bytesBkRet[24]);
							tmpFinished = false;
							tmpFileMsg = "不能识别的应答类型：" + (char) bytesBkRet[24];
							break;
						}
					}
				} else {
					tmpFinished = false;
					tmpFileInfoCode = "E9999";
					tmpFileMsg = tmpBkRet[1];
					break;
				}
			}
			
			if (tmpFinished) {
				// 发起文件确认(B60911/I60911)
				WriteBankLogLn("2.文件发送成功，进行文件确认，连接服务：" + bankFront.serverIP + ":" + bankFront.serverPort);
				
				BOCOM13Header tmpBankHeader = new BOCOM13Header();
				tmpBankHeader.transCode = "I60911";
				tmpBankHeader.reqSeqID = p_req.reqSeqID;
				tmpBankHeader.corpNo = corpNo;
				
				XmlTextWriter xmlWriter = new XmlTextWriter();
				writeCommonHeader(xmlWriter, tmpBankHeader);

				xmlWriter.writeStartElement("Body");
				xmlWriter.writeElementString("FileName", tmpUploadFileName + ".gz");/* 压缩文件名称 */
				xmlWriter.writeElementString("TotalNum", p_req.totalNum);/* 总笔数 */
                xmlWriter.writeElementString("TotalAmt", "0.00");/* 总金额 */
				xmlWriter.writeElementString("BatNo", p_req.reqSeqID);/* 创建方批次号 */
				xmlWriter.writeEndDocument();

				String[] tmpRetStr = sendToBank(xmlWriter.toXmlString(), bankFront.serverPort);
				
				if (tmpRetStr[0].length() == 0) {
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
					if (tmpBkReader != null) {
						retAts.respCode = "0";
						retAts.respInfo = tmpBkReader.getFirstText("/Rsp/Head/ErrMsg");
						String tmpMsgType = tmpBkReader.getFirstText("/Rsp/Head/MsgType");
						String tmpErrCode = tmpBkReader.getFirstText("/Rsp/Head/ErrCode");
						if ("N".equals(tmpMsgType) && "000000".equals(tmpErrCode)) {
							retAts.retCode = "2";
						} else {
							retAts.retCode = "1";
						}
						retAts.retMsg = retAts.respInfo;
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = tmpSbMsg.toString();
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpRetStr[1];
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpFileInfoCode + "+" + tmpFileMsg;
			}
        } catch (Exception ex) {
        	ex.printStackTrace();
        	retAts.respCode = "-1";
        	retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
			if (tmpClient != null) {
				if (tmpClient.socket != null) {
					tmpClient.socket.close();
				}
				if (tmpClient.tmpOutput != null) {
					tmpClient.tmpOutput.close();
				}
				if (tmpClient.tmpInput != null) {
					tmpClient.tmpInput.close();
				}
			}
			if (fis != null) {
			    fis.close();
            }
			if (fos != null) {
			    fos.close();
            }
		}
        
        retAts.writeRetToATS();
        return retAts;
	}

	@Override
	public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) throws Exception {
		RetAtsQryAuthForRec retAts = new RetAtsQryAuthForRec(p_req.reqHeader);
		retAts.reqSeqID = p_req.reqSeqID;
        retAts.writeStart();
        
        try {
        	String tmpNotifyDataPath = getNotifyDirectory() + File.separator + p_req.reqSeqID + ".txt";
			WriteBankLogLn("银行结果文件路径:" + tmpNotifyDataPath);
			
			if (new File(tmpNotifyDataPath).exists()) {
				String tmpStrRet = FileHelper.readFileText(tmpNotifyDataPath, getCharset());
				WriteBankLogLn("银行结果文件内容:\r\n" + tmpStrRet);
                StringReader strReader = new StringReader(tmpStrRet);
                BufferedReader tmpReader = new BufferedReader(strReader);
                String[] line1 = tmpReader.readLine().split("\u000F");
				if (line1.length > 10) {
					String tmpBkBatNO = line1[10];
					if (p_req.reqSeqID.equals(tmpBkBatNO)) {
						retAts.respCode = "0";
						while(true) {
                            String tmpLine = tmpReader.readLine();
                            if (tmpLine == null) {
                                break;
                            }
                            String[] eachLine = tmpLine.split("\u000F");
                            RetAtsQryAuthForRecDetail tmpRetDetail = new RetAtsQryAuthForRecDetail();

                            tmpRetDetail.iSeqno = eachLine[7];

                            String tmpBkDtState = eachLine[1];
                            String tmpBkDtInfoCode = eachLine[2];
                            String tmpBkDtInfo = eachLine[3];
                            if ("N".equals(tmpBkDtState) && "000000".equals(tmpBkDtInfoCode)) {
                                tmpRetDetail.transState = "2";
                            } else {
                                tmpRetDetail.transState = "3";
                            }
                            tmpRetDetail.payCode = tmpBkDtInfoCode;
                            tmpRetDetail.payInfo = tmpBkDtInfo;
                            if (eachLine.length > 12) {
                                tmpRetDetail.oppAct = eachLine[13];
                            }
                            tmpRetDetail.oppActName = eachLine[10];
                            if (eachLine.length > 15) {
                                tmpRetDetail.newAuthCode = eachLine[15];
                            }

                            retAts.writeRetDetail(tmpRetDetail);
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "结果文件中的批次号" + tmpBkBatNO + "与请求批次号" + p_req.reqSeqID + "不一致";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "结果文件格式不符合预期，首行字段数不足16个";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "当前未收到交行的结果通知文件，请稍后查询！";
			}
        } catch (Exception ex) {
        	ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        
        retAts.writeAfterDetail();
        return retAts;
	}

	@Override
	public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
		RetAtsQryRecAuthInfo retAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
		retAts.ownAct = p_req.ownAct;

		try {
			String corpNo = getBankConfig().getMapValueByKey("corpNoMapping", p_req.ownAct);
			if (StringHelper.isNullOrEmpty(corpNo)) {
				retAts.respCode = "0";
				retAts.respInfo = "未找到账号:[" + p_req.ownAct + "]对应的保险方ID，暂无权限获取,请检查'portfiles/BOCOM13/config.xml'中'corpNoMapping'配置是否正确!";
				retAts.writeAfterDetail();
				return retAts;
			}

			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(Format.Date8Format.parse(p_req.dateFrom));

			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(Format.Date8Format.parse(p_req.dateTo));

			int tmpIntDateFrom = 0;
			int tmpIntDateTo = 0;
			//按自然月循环查询
			while (tmpIntDateFrom <= tmpIntDateTo) {
				Calendar tmpClndrStepTo = Calendar.getInstance();
				tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
				//判断是否跨月
				if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
					//跨月则设置为月末
					tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
				} else {
					tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
				}

				String tmpNotifyDataPath = getNotifyDirectory() + File.separator + "qry_authInfo_" + Format.Date8Format.format(tmpCalendarFrom.getTime()) + ".txt";

				boolean useAuthInfoFilePath = getBankConfig().getValueAsBool("useAuthInfoFilePath");
				WriteBankLogLn("查询签约用户信息是否读取固定配置下的路径:"+useAuthInfoFilePath);
				if (useAuthInfoFilePath) {
					String authInfoFilePath = getBankConfig().getValueAsString("authInfoFilePath");
					if (StringHelper.hasAnyChar(authInfoFilePath)) {
						String dateFrom = Format.Date8Format.format(tmpCalendarFrom.getTime());
						tmpNotifyDataPath =  StringHelper.trimEnd(authInfoFilePath,"\\") + File.separator + "BOCOM13" + File.separator + "PayResultNotify" + File.separator + "qry_authInfo_" + Format.Date8Format.format(tmpCalendarFrom.getTime()) + ".txt";
					}
				}
				WriteBankLogLn("银行结果文件路径:" + tmpNotifyDataPath);

				if (new File(tmpNotifyDataPath).exists()) {
					String tmpStrRet = FileHelper.readFileText(tmpNotifyDataPath, getCharset());
					WriteBankLogLn("银行结果文件内容:\r\n" + tmpStrRet);
					StringReader strReader = new StringReader(tmpStrRet);
					BufferedReader tmpReader = new BufferedReader(strReader);
					tmpReader.readLine();

					retAts.respCode = "0";
					while(true) {
						String tmpLine = tmpReader.readLine();
						if (tmpLine == null) {
							break;
						}
						String[] eachLine = tmpLine.split("\u000F");
						RetAtsQryRecAuthInfoDetail tmpRetDetail = new RetAtsQryRecAuthInfoDetail();
						tmpRetDetail.oppAct = eachLine[13];
						tmpRetDetail.oppActCur = p_req.oppCur;
						tmpRetDetail.oppActName = eachLine[10];
						tmpRetDetail.queryTag = p_req.queryTag;
						tmpRetDetail.insuPolicyNum = eachLine[8];
						tmpRetDetail.sourceNoteCode = eachLine[9];
						tmpRetDetail.newAuthCode = eachLine[14];
						tmpRetDetail.signDate = eachLine[6];
						tmpRetDetail.certType = convertCertTypeToBank(eachLine[11]);
						tmpRetDetail.certNum = eachLine[12];
						retAts.writeRetDetail(tmpRetDetail);
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "当前未收到交行的结果通知文件，请稍后查询！";
				}

				tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
				tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
				tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeAfterDetail();
		return retAts;
	}
}